package org.jeecg.common.util;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.concurrent.TimeUnit;

@RestController
public class HttpClientUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;//注入redis
    @Value("${uniubi.appKey}")
    private String appKey;
    @Value("${uniubi.appSecret}")
    private String appSecret;
    @Value("${uniubi.projectGuid}")
    private String projectGuid;
    private static Long timestamp;
    @Value("${rms.username}")
    private String username;
    @Value("${rms.password}")
    private String password;


    /**
     * 判断token是否过期,没过期返回token,过期重新获取在返回
     */
    public String estimateToken(){
        if(redisTemplate.hasKey("token")){
            if (redisTemplate.opsForValue().get("token")==null){
                redisTemplate.delete("token");
                getToken();
            }
            return (String) redisTemplate.opsForValue().get("token");
        }else {
            getToken();
        }
        return (String) redisTemplate.opsForValue().get("token");
    }

    /**
     * 获取token
     */
    public void getToken() {
        String url = "http://wo-api.uni-ubi.com/v1/" + projectGuid + "/auth";
        timestamp = System.currentTimeMillis();
        JSONObject param = new JSONObject();
        param.put("projectGuid",projectGuid);
        JSONObject response = RestUtil.get(url, getTokenHeaders(appKey, timestamp, getSign()), param);
        Object data = response.get("data");
        String token = data.toString();
        redisTemplate.opsForValue().set("token", token);//将token交给redis管理
        redisTemplate.expire("token", 20, TimeUnit.HOURS);
    }


    /**
     * 获取盐
     *
     * @return
     */
    public String getSign() {
        String sign;
        MessageDigest md5;
        String encryptStr = appKey + timestamp + appSecret;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            //默认小写，在tostring后加toUpperCase()即为大写加密
            sign = hexValue.toString();
            System.out.println(timestamp);
            System.out.println(sign);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sign;
    }

    /**
     * token的请求头
     * @param appKey
     * @param timestamp
     * @param sign
     * @return
     */
    public HttpHeaders getTokenHeaders(String appKey,Long timestamp,String sign){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("appKey",appKey);
        httpHeaders.add("timestamp",timestamp.toString());
        httpHeaders.add("sign",sign);
        return httpHeaders;
    }

    /**
     * 其他请求的请求头
     */
    public HttpHeaders postHeaders(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("requestId", "{{$guid}}");
        httpHeaders.add("clientCode", "geekCode");
        httpHeaders.add("warehouseCode", "geekCode");
        httpHeaders.add("userId", username);
        httpHeaders.add("userKey", password);
        httpHeaders.add("language", "en_us");
        httpHeaders.add("version", "3.3.0");
        /*httpHeaders.add("token", estimateToken());
        httpHeaders.add("projectGuid",projectGuid);
        httpHeaders.add("Content-Type","application/json");*/
        return httpHeaders;
    }


    public  JSONObject doPost(String url,Object params){
        String paramString = JSONObject.toJSONString(params);
        JSONObject requestParam = JSONObject.parseObject(paramString);
        JSONObject response = RestUtil.post(url, postHeaders(), requestParam);
        return response;
    }


}